<?php
/**
 * Model for News Component
 * @subpackage  news component
 * @license GNU/GPL
 */
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');
require_once(JPATH_COMPONENT_ADMINISTRATOR.DS.'models'.DS.'layouttemplates.php');

/**
 * Sectionslayout Model
 *
 * @package    Joomla
 * @subpackage Components
 */
class JanewsModelsectionslayout extends JanewsModellayouttemplates
{	
	/**
	 * @return total sections
	 */
	function getTotal()
	{
		$db = JFactory::getDBO();
		$query = 'SELECT count(*) FROM #__sections';
		$db->setQuery($query);
		$num = $db->loadResult();
		return $num;
	}

	/*function getSectionLayout($s_id)
	{
		
		$db = JFactory::getDBO();
		$query = 'SELECT t.title '
		.'FROM #__janews_templates AS t, #__janews_sections AS s'
		.' WHERE s.secid = '.$s_id.' AND t.id IN ( s.headline, s.blog)';
		$db->setQuery($query);
		$tmpl = $db->loadResultArray();
		return $tmpl;
	}*/

	/**
	 * Retrieves the sections data
	 * @return array Array of objects containing the data from the table sections
	 */
	function getListSections($filter_order='', $filter_order_Dir='', $limit='', $limitstart='')
	{ 
		$db =& JFactory::getDBO();
		$query = "SELECT s.id, s.title, s.published as published, b.headline AS headline, b.blog AS blog"
		." FROM  #__sections AS s LEFT JOIN #__janews_sections AS b"
		." ON s.id = b.secid";
		$query 	.= ' ORDER BY '.$filter_order.' '. $filter_order_Dir .', s.ordering';
		if ($limit=='' && $limitstart==''){
			$db->setQuery( $query);
		}else{
			$db->setQuery( $query, $limitstart, $limit);
		}

		$listsections = $db->loadObjectList();
		return $listsections;
	}
	
	/**
	 * @return published categories of the section
	 */
	function getListCats($s_id)
	{
		$db =& JFactory::getDBO();
		$query = 'SELECT id AS value, concat(concat(title,"\ ("), concat(id,"\) ") ) AS text'
		  .' FROM #__categories'
		  .' WHERE section = '.$s_id.' and published = 1 ORDER BY ordering';
		$db->setQuery( $query );
		$list_cat = $db->loadObjectList();
		return $list_cat;
	}
	
	/**
	 * @param ID of the section
	 * @return selected categories of the section 
	 */
	function getSelectedCats($s_id)
	{
		if ($s_id) {
			$str = $this->getStrCatIds($s_id);
			$db = JFactory::getDBO();
			$query = 'SELECT id AS value, concat(concat(title,"\ ("), concat(id,"\) ") ) AS text '
			  .' FROM #__categories'
			  .' WHERE section ='.$s_id.' and id IN ('."$str".')';
			$list = $this->_getList($query);
			$sort = JArrayHelper::toObject(split(',',$str));
			
			foreach ($sort as $i => $id) {
			  foreach ($list as $j => $v) {
			    if ($v->value==$id) {
			      $tmp = new stdClass();
			      $tmp = $list[$j];
			      $list[$j] = $list[$i];
			      $list[$i] = $tmp;
			    }
			  }
			}
		}
		return $list;
	}
	
	/**
	 * @param ID of the section
	 * @return string selected cat_id of the section 
	 */
	function getStrCatIds($s_id)
	{
		if ($s_id) {
			$db = JFactory::getDBO();
			$query = 'SELECT categories FROM #__janews_sections WHERE secid ='.$s_id;
			$db->setQuery($query);
			$rs = $db->loadResult();
		}
		return $rs;
	}
	
	/**
	 * @param category id
	 * @return record of #__categories table
	 */
	function getInfoCategory($catid)
	{
	  $db = JFactory::getDBO();
	  $query = "SELECT * FROM #__categories WHERE id = ".$catid;
	  $db->setQuery($query);
	  $rs = $db->loadObject();
	  return $rs;
	}
	
	/**
	 * @param ID of the section
	 * @return string list cat_ids of the section 
	 */
	function getStrListCatIds($s_id)
	{
		if ($s_id) {
			$db = JFactory::getDBO();
			$query = 'SELECT id FROM #__categories '.
							 'WHERE section ='.$s_id.' and published = 1 ORDER BY ordering';
			$db->setQuery($query);
			$str_list = implode(',', $db->loadResultArray());
		}
		return $str_list;
	}
	
	/**
	 * @param ID of the section
	 * @return info JAsections (contain title, params, headline and blog template)
	 */
	function getJASectionInfo($s_id)
	{
		if ($s_id) {
			$db = JFactory::getDBO();
			$query = 'SELECT id, title, headline, blog
								FROM #__sections, #__janews_sections
								WHERE	id = secid and	secid = '.$s_id;
			$db->setQuery($query);
			$rs = $db->loadObject();
		}
		return $rs;
	}
	
	/**
	 * @param ID of the section
	 * @return info sections table of Joomla (id, title)
	 */
	function getSectionInfo($s_id)
	{
		if ($s_id) {
			$db = JFactory::getDBO();
			$query = 'SELECT id, title FROM #__sections WHERE	id = '.$s_id;
			$db->setQuery($query);
			$rs = $db->loadObject();
		}
		if (!$rs){
			JError::raiseError(404, JText::_("Resource Not Found"));
		}
		return $rs;
	}
	
	/**
	 * Update menus for all category
	 * @param sectionid
	 * @param string categories id of the section display
	 */
	function createMenuCategories($s_id, $params, $layout)
	{
	  //delelte all menu of categories
	  $db = JFactory::getDBO();
	  
	  $query = "SELECT *"
		  ." FROM #__menu"
		  ." WHERE menutype='janews' AND type='component' AND link='index.php?option=com_janews&view=section&layout=blog&id=".$s_id."'";
		$db->setQuery($query);
		$msec = $db->loadObject();
	  
	  $query = "DELETE FROM #__menu"
	    ." WHERE menutype = 'janews' AND parent = ".$msec->id;
	  $db->setQuery($query);
	  $db->query();
	  //creat menu for categories to display
	  switch ($layout){
	    case 1:
	      $link = 'index.php?option=com_content&view=category&layout=blog&id=';
	      $component =& JComponentHelper::getComponent('com_content');
	      break;
	    case 2:
	      $link = 'index.php?option=com_content&view=category&id=';
	      $component =& JComponentHelper::getComponent('com_content');
	      break;
	    case 3:
	      $link = 'index.php?option=com_janews&view=category&id=';
	      $component =& JComponentHelper::getComponent('com_janews');
	      break;
	  }
	  $catids = split(',',$this->getStrCatIds($s_id));
	  for ($i=0;$i<count($catids);$i++) {
	    $cat = $this->getInfoCategory($catids[$i]);
	    $order = $i +1;
	    $query = "INSERT INTO #__menu (menutype,name,alias,link,type,published,parent,
		  componentid,sublevel,ordering,checked_out,checked_out_time,pollid,browserNav,access,utaccess,params)"
	    ." VALUES ('janews','".addslashes($cat->title)."','".addslashes($cat->alias)."' ,'".$link.$cat->id."',
	    'component','1','".$msec->id."','".$component->id."','1','".$order."','0','0000-00-00 00:00:00','0','0','0','0',
	    '".$params."')";
	    $db->setQuery($query);
	    $db->query();
	  }	  
	}

	/**
	 * @return list Categories view layout type for select 
	 */
	function getCategoryLayoutType()
	{
		$arr = JArrayHelper::toObject( $a = array("value" => "0", "text" => "-Select categories layout-"));
		$catblog = JArrayHelper::toObject( $a = array("value" => "1", "text" => "Category blog layout"));
		$catlist = JArrayHelper::toObject( $a = array("value" => "2", "text" => "Category list layout"));
		$catjanews = JArrayHelper::toObject( $a = array("value" => "3", "text" => "Category janews layout"));
		$rs = array("0" => $arr, "1" => $catblog, "2" => $catlist, "3" => $catjanews);
		return $rs;
	}
	
	function checkMenuSection($s_id)
	{
	  $db = JFactory::getDBO();
	  $query1 = "SELECT *"
		  ." FROM #__menu"
		  ." WHERE menutype='janews' AND type='component' AND link='index.php?option=com_janews&view=section&layout=blog&id=".$s_id."'";
		$db->setQuery($query1);
		$msec = $db->loadObject();
		if (!$msec){
		  $query = "SELECT id, title, alias"
			   ." FROM #__sections"
		     ." WHERE id = ".$s_id;
	     $db->setQuery($query);
	     $sec = $db->loadObject();
	     if ($sec){
	       $query = "SELECT count(*)"
          ." FROM #__menu"
          ." WHERE menutype='janews' AND type='component' AND link LIKE 'index.php?option=com_janews&view=section&layout=blog&id=%'";
        $db->setQuery($query);
        $num = $db->loadResult();
        $order = $num ? $num+1 : 1;
        $component =& JComponentHelper::getComponent('com_janews');
        $query = "INSERT INTO #__menu (menutype,name,alias,link,type,published,parent,
          componentid,sublevel,ordering,checked_out,checked_out_time,pollid,browserNav,access,utaccess,params)"
          ." VALUES ('janews','".addslashes($sec->title)."','".addslashes($sec->title)."','index.php?option=com_janews&view=section&layout=blog&id=".$sec->id."','component','1','0',
          '".$component->id."','0','".$order."','0','0000-00-00 00:00:00','0','0','0','0','menu_image=-1')";
        $db->setQuery( $query );
        $db->query();
        $db->setQuery($query1);
		    $msec = $db->loadObject();
	     }
	     else {
	       return false;
	     }
		}
		return $msec;
	}
	
	function getSectionParams($id)
	{
	  $file 	= JPATH_COMPONENT_ADMINISTRATOR.DS.'views'.DS.'sectionslayout'.DS.'secparams.xml';
	  $this->checkMenuSection($id);
	  $db = JFactory::getDBO();
	  $query = "SELECT params"
      ." FROM #__janews_sections"
      ." WHERE secid = ".$id;
    $db->setQuery($query);
	  $secparams = $db->loadResult();
		$secparams = new JParameter($secparams, $file);
		return $secparams;
	}
	
  function getMenuCategoryParams($s_id)
  {
    $db = JFactory::getDBO();
    $msec = $this->checkMenuSection($s_id);
    $component =& JComponentHelper::getComponent('com_content');
    $query = "SELECT params"
      ." FROM #__menu"
      ." WHERE menutype='janews' AND componentid = ".$component->id." AND parent = ".$msec->id;
    $db->setQuery($query);
    $catparams = $db->loadResult();
    $file 	= JPATH_COMPONENT_ADMINISTRATOR.DS.'views'.DS.'sectionslayout'.DS.'catparams.xml';
    $catparams = new JParameter($catparams, $file);
    return $catparams;
  }
}

?>